﻿using CCWin;
using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace NMLX_ProgramGuardians
{
    public partial class ProgramGuardians : Skin_Color
    {
        System.Timers.Timer timer;
        //守护进程
        //private static readonly string ProgramName = ConfigurationManager.AppSettings["ProgramName"].ToString();
        //检查间隔
        private static readonly int timerInterval = Convert.ToInt32(ConfigurationManager.AppSettings["timerInterval"]) * 1000;


        //字段
        private string[] _processAddress;
        private object _lockerForLog = new object();
        private string _logPath = string.Empty;
        public ProgramGuardians()
        {
            InitializeComponent();
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                //还原窗体显示    
                WindowState = FormWindowState.Normal;
                //激活窗体并给予它焦点
                this.Activate();
                //任务栏区显示图标
                this.ShowInTaskbar = true;
                //托盘区图标隐藏
                notifyIcon1.Visible = false;
            }
        }

        private void ProgramGuardians_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("是否确认退出程序？", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                // 关闭所有的线程
                this.Dispose();
                this.Close();
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void ProgramGuardians_SizeChanged(object sender, EventArgs e)
        {
            //判断是否选择的是最小化按钮
            if (WindowState == FormWindowState.Minimized)
            {
                //隐藏任务栏区图标
                this.ShowInTaskbar = false;
                //图标显示在托盘区
                notifyIcon1.Visible = true;
            }
        }

        private void 显示ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            WindowState = FormWindowState.Normal;
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否确认退出程序？", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                // 关闭所有的线程
                this.Dispose();
                this.Close();
            }
        }

        private void ProgramGuardians_Load(object sender, EventArgs e)
        {
            //初始化Timer
            InitTimer();
            this.skinButton2.Enabled = false;
            try
            {
                //读取监控进程全路径
                string strProcessAddress = ConfigurationManager.AppSettings["ProcessAddress"].ToString();
                if (strProcessAddress.Trim() != "")
                {
                    this._processAddress = strProcessAddress.Split(',');
                }
                else
                {
                    throw new Exception("读取配置ProcessAddress失败，ProcessAddress为空！");
                }
                //创建日志目录
                this._logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log");
                if (!Directory.Exists(_logPath))
                {
                    Directory.CreateDirectory(_logPath);
                }
            }
            catch (Exception ex)
            {
                this.SaveLog("Log()初始化出错！错误描述为：" + ex.Message.ToString());
            }




        }
        /// <summary>
        /// 初始化timer
        /// </summary>
        private void InitTimer()
        {
            //设置定时间隔(毫秒为单位)
            int interval = timerInterval;
            timer = new System.Timers.Timer(interval);
            //设置执行一次（false）还是一直执行(true)
            timer.AutoReset = true;
            //设置是否执行System.Timers.Timer.Elapsed事件
            timer.Enabled = false;
            //绑定Elapsed事件
            timer.Elapsed += new System.Timers.ElapsedEventHandler(TimerUp);
        }
        private void TimerUp(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                if (this._processAddress != null)
                {
                    if (this._processAddress.Length > 0)
                    {
                        foreach (string str in _processAddress)
                        {
                            if (str.Trim() != "")
                            {
                                if (File.Exists(str.Trim()))
                                {
                                    this.Guardian(str.Trim());
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.SaveLog(ex.Message);
            }
        }

        private void skinButton1_Click(object sender, EventArgs e)
        {
            this.skinButton1.Enabled = false;
            this.skinButton2.Enabled = true;
            timer.Start();
        }

        private void skinButton2_Click(object sender, EventArgs e)
        {
            this.skinButton1.Enabled = true;
            this.skinButton2.Enabled = false;
            timer.Stop();
        }

        /// <summary>
        /// 守护进程
        /// 扫描进程列表，判断进程对应的全路径是否与指定路径一致
        /// 如果一致，说明进程已启动
        /// 如果不一致，说明进程尚未启动
        /// </summary>
        private void Guardian(string address)
        {
            bool isStart = false;
            Process[] arrayProcess = Process.GetProcesses();
            foreach (Process p in arrayProcess)
            {

                try
                {
                    if (this.FormatPath(address) == this.FormatPath(p.MainModule.FileName.ToString()))
                    {
                        isStart = true;
                    }
                }
                catch
                {
                    //拒绝访问进程的全路径
                    //this.SaveLog("进程(" + p.Id.ToString() + ")(" + p.ProcessName.ToString() + ")拒绝访问全路径！");
                }

            }
            if (!isStart)
            {
                isStart = false;
                //进程尚未启动
                Process process = new Process();
                process.StartInfo.FileName = address;
                try
                {
                    process.Start();
                }
                catch (Exception ex)
                {

                    this.SaveLog("错误描述"+ex.Message);
                }
            }
        }
        /// <summary>
        /// 格式化路径
        /// 去除前后空格
        /// 去除最后的"\"
        /// 字母全部转化为小写
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private string FormatPath(string path)
        {
            return path.ToLower().Trim().TrimEnd('\\');
        }


        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="content"></param>
        public void SaveLog(string content)
        {
            try
            {
                lock (_lockerForLog)
                {
                    FileStream fs;
                    fs = new FileStream(Path.Combine(this._logPath, DateTime.Now.ToString("yyyyMMdd") + ".log"), FileMode.OpenOrCreate);
                    StreamWriter streamWriter = new StreamWriter(fs);
                    streamWriter.BaseStream.Seek(0, SeekOrigin.End);
                    streamWriter.WriteLine("[" + DateTime.Now.ToString() + "]：" + content);
                    streamWriter.Flush();
                    streamWriter.Close();
                    fs.Close();
                }
            }
            catch
            {
            }
        }
    }
}


